import recomApi from '@/api/oen/RecomApi'
import bizSegmentApi from '@/api/oen/BizSegmentApi'
import { deepClone, changeDecimal } from '@/utils/common'
import { handleServiceI18n } from '@/service/i18n'

export default {
  data() {
    return {
      routeCount: 0,
      obtainedCount: 0,
      recommended: false,
      originalCabcle: [],
      routeResult: [],
      exclusiveChannelId: []
    }
  },
  updated() {
    this.formData.necessaryCable = this.formData.necessaryCable || []
    this.formData.forbiddenCable = this.formData.forbiddenCable || []
    this.formData.necessaryStation = this.formData.necessaryStation || []
    this.formData.forbiddenStation = this.formData.forbiddenStation || []
  },
  methods: {
    rerecommend(operateType) {
      if (operateType === 'restore') {
        this.showFilter = true
        this.$nextTick(() => {
          this.$refs.filterItem.setFormData()
        })
        return
      }
      this.getRouteList(operateType)
    },
    // 获取推荐路由列表
    getRouteList(operateType) {
      this.showFilter = false
      this.originalCabcle = []
      this.recommended = true
      this.routeCount = 0
      this.obtainedCount = 0
      this.expandRow = []
      this.routeList = []
      const startPorts = [this.formData.aPortData.portId]
      const endPorts = [this.formData.zPortData.portId]
      if (
        this.formData.aPortData2 &&
        this.formData.aPortData2.portId &&
        this.formData.zPortData2 &&
        this.formData.zPortData2.portId
      ) {
        startPorts.push(this.formData.aPortData2.portId)
        endPorts.push(this.formData.zPortData2.portId)
      }
      // console.log('this.formData', this.formData)
      this.xclusiveChannelId = []
      Promise.all([
        recomApi.linkRecom({
          bizId: this.formData.bizId || null,
          startNodeId: this.formData.aNodeData
            ? this.formData.aNodeData.nodeId
            : this.formData.aPortData.nodeId,
          endNodeId: this.formData.zNodeData
            ? this.formData.zNodeData.nodeId
            : this.formData.zPortData.nodeId,
          startPortIdList: startPorts.join(),
          endPortIdList: endPorts.join(),
          recomType: operateType.toUpperCase()
        }),
        operateType === 'back' && bizSegmentApi.channelList({ exclusive: true })
      ])
        .then(res => {
          const exclusiveRes = res[1] || []
          this.exclusiveChannelId = exclusiveRes.map(i => i.segmentChannelId)
          const result = res[0] || []
          const routeResult = []
          result.forEach((i, index) => {
            if (i.original) {
              this.originalCabcle = i.segmentList.filter(j => j.cableId).map(j => j.cableId)
            }
            const { necessaryCable, forbiddenCable, necessaryStation, forbiddenStation } =
              this.formData
            const stationList = []
            const cableList = []
            i.segmentList.forEach(j => {
              stationList.push(j.startNodeId)
              stationList.push(j.startNode.stationId)
              j.startNode.roomId && stationList.push(j.startNode.roomId)
              stationList.push(j.endNodeId)
              stationList.push(j.endNode.stationId)
              j.endNode.roomId && stationList.push(j.endNode.roomId)
              j.cableId && cableList.push(j.cableId)
            })
            const canPush =
              necessaryCable.every(i => cableList.includes(i)) &&
              !forbiddenCable.some(i => cableList.includes(i)) &&
              necessaryStation.every(i => stationList.includes(i)) &&
              !forbiddenStation.some(i => stationList.includes(i))
            canPush &&
              routeResult.push({
                ...i,
                routeLinkId: index + ',' + i.segmentList.map(j => j.id).join(),
                channelList: [],
                baseAmong: []
              })
          })
          if (routeResult.length === 0) {
            this.obtainedCount = 1
            this.$message.warning(this.$t('NO_RECOMMENDED_ROUTE'))
            return
          }
          this.routeCount = routeResult.length
          this.routeResult = routeResult
          this.routeResult.forEach(i => {
            this.getChannelList(i, operateType)
          })
          this.mouseEvent && this.mouseEvent(this.routeList[0], 'always')
          this.recommended = false
          // this.sortRouteList()
        })
        .catch(() => {
          this.recommended = false
        })
    },
    // 路由排序
    sortRouteList(type) {
      this.routeList.sort((a, b) => {
        if (this.routeSort === 'linkLength') {
          if (b.linkLength === a.linkLength) {
            return b.nodeNum > a.nodeNum ? 1 : -1
          }
          return b.linkLength > a.linkLength ? 1 : -1
        } else {
          if (b.nodeNum === a.nodeNum) {
            return b.linkLength > a.linkLength ? 1 : -1
          }
          return b.nodeNum > a.nodeNum ? 1 : -1
        }
      })
      if (navigator.userAgent.indexOf('Firefox') >= 0) {
        this.routeList.reverse()
      }
      this.routeList.sort((a, b) => {
        return a.original ? 1 : -1
      })
      this.highlightData = this.routeList[0] || []
    },
    getChannelList(data, operateType) {
      const startPorts = [this.formData.aPortData.portId]
      const endPorts = [this.formData.zPortData.portId]
      if (
        this.formData.aPortData2 &&
        this.formData.aPortData2.portId &&
        this.formData.zPortData2 &&
        this.formData.zPortData2.portId
      ) {
        startPorts.push(this.formData.aPortData2.portId)
        endPorts.push(this.formData.zPortData2.portId)
      }
      recomApi
        .channelRecom({
          bizId: this.formData.bizId || null,
          startNodeId: this.formData.aNodeData
            ? this.formData.aNodeData.nodeId
            : this.formData.aPortData.nodeId,
          endNodeId: this.formData.zNodeData
            ? this.formData.zNodeData.nodeId
            : this.formData.zPortData.nodeId,
          startPortIdList: startPorts.join(),
          endPortIdList: endPorts.join(),
          struct: data.segmentList.map(i => i.segmentId).join(),
          recomType: operateType.toUpperCase()
        })
        .then(res => {
          if (!res) return
          if (operateType === 'back') {
            const canNext = this.delRepeat(res)
            if (!canNext) {
              // this.$message.error(this.$t('NO_RESOURCES_RECOMMEND'))
              return
            }
          }
          res.recomResult.LOSS = this.formatChannel(res.recomResult, 'LOSS')
          res.recomResult.TIME = this.formatChannel(res.recomResult, 'TIME')
          this.formatAmong(data, res.logicMatrix)
          data.channelList = [...res.recomResult.LOSS, ...res.recomResult.TIME]
          data.logicMatrix = deepClone(res.logicMatrix)
          data.linkLength = changeDecimal(data.linkLength, 3, true)
          if (data.channelList.length > 0) {
            this.routeList.push(data)
            this.sortRouteList()
          }
          // this.routeDetailShow = true
        })
        .catch(() => {})
        .finally(() => {
          this.obtainedCount++
          if (this.obtainedCount === this.routeCount && this.routeList.length === 0) {
            this.$message.warning(this.$t('NO_RECOMMENDED_ROUTE'))
            return
          }
        })
      data.obtainedChannel = true
    },
    /**
     * 过滤主用通道
     * @param {*} data
     * 1.获取主用通道里面的channel集合 => mainChannel
     * 2.过滤掉逻辑网段里面除去首尾逻辑网段里面包含mainChannel的逻辑网段 => logicMatrix
     * 3.判断logicMatrix是否有足够可选的逻辑通道，没有就弹出提示
     * 4.判断推荐的链损最小'LOSS'和耗时最少'TIME'里面逻辑网段除去首尾的，
     * true => 如果逻辑网段包含主用mainChannel 用'logicMatrix'对应的逻辑网段替换
     * false => 保持不变
     * @returns
     */
    delRepeat(data) {
      const count = this.formData.mainChannelList.length
      const mainChannel = [...this.exclusiveChannelId]
      this.formData.mainChannelList.forEach(i => {
        i.channelList.forEach(j => {
          mainChannel.push(j.channelId)
        })
      })
      data.logicMatrix.forEach((i, index) => {
        if (index !== 0 && index !== data.logicMatrix.length - 1) {
          data.logicMatrix[index] = i.filter(
            j => !j.physicStruct.some(z => mainChannel.includes(z.channelId))
          )
        }
      })
      if (
        data.logicMatrix.some(
          (i, index) => index !== 0 && index !== data.logicMatrix.length - 1 && i.length < count
        )
      ) {
        return false
      }
      data.recomResult.LOSS = this.changeMain(data, mainChannel, data.recomResult.LOSS)
      data.recomResult.TIME = this.changeMain(data, mainChannel, data.recomResult.TIME)
      return true
    },
    // 获取割接信息
    async getCutoverList(data) {
      data.isReach = false
      const res = await recomApi.logicChannelAnalyze(data.physicSegmentList)
      data.isReach = true
      data.cutoverList = res.cutoverList || []
      data.cutoverNum = res.cutoverNum
      data.cutoverTime = res.cutoverTime
      data.loss = res.loss
    },
    // 修改推荐出的主用为其他逻辑通道
    changeMain(data, mainChannel, linkData) {
      linkData.forEach((i, iIndex) => {
        let needReget = false
        i.segmentList.forEach((j, jIndex) => {
          if (
            jIndex !== 0 &&
            jIndex !== i.segmentList.length - 1 &&
            j.physicStruct.some(z => mainChannel.includes(z.channelId))
          ) {
            i.segmentList[jIndex] = data.logicMatrix[jIndex][iIndex]
            needReget = true
          }
        })
        needReget &&
          this.$nextTick(() => {
            this.getCutoverList(i)
          })
      })
      return linkData
    },
    // 格式化显示的通道
    formatChannel(data, type) {
      data[type].forEach(i => {
        i.checked = false
        i.exclusive = 'SHARE'
        i.channelType = type
        i.physicSegmentList = deepClone(i.segmentList)
        let segmentList = []
        i.segmentList.forEach((j, index) => {
          segmentList = [
            ...segmentList,
            ...j.physicStruct.map(z => {
              return {
                ...z,
                segmentSort: j.segmentSort
              }
            })
          ]
        })
        i.segmentList = [...segmentList]
        segmentList.forEach((j, index) => {
          j.startPort.bizName = handleServiceI18n(j.startPort.bizName)
          j.endPort.bizName = handleServiceI18n(j.endPort.bizName)
          i['segmentList' + index] = j
        })
      })
      return data[type]
    },
    // 格式化可选择的逻辑通道
    formatAmong(data, logicMatrix) {
      const amongChannel = {}
      let typeNum = 1
      if (this.formData.aPortData2 && this.formData.aPortData2.portId) {
        typeNum = 2
      }
      logicMatrix.forEach(i => {
        // 可选数量大于单双芯数量
        if (i.length > typeNum) {
          i.forEach(j => {
            // 拼接到每个可选通道
            j.physicStruct.forEach(z => {
              z.startPort.bizName = this.$utils.handleServiceI18n(z.startPort.bizName)
              z.endPort.bizName = this.$utils.handleServiceI18n(z.endPort.bizName)
              const item = {
                logicSegmentId: j.segmentId,
                segmentSort: j.segmentSort,
                ...z
              }
              if (amongChannel[z.segmentId]) {
                amongChannel[z.segmentId].push(item)
              } else {
                amongChannel[z.segmentId] = [item]
              }
            })
          })
          data.baseAmong = [...data.baseAmong, ...i]
        }
      })
      data.amongChannel = amongChannel
    }
  }
}
